package com.sun.wanandroid.ui.login

import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.guru.fontawesomecomposelib.FaIcon
import com.guru.fontawesomecomposelib.FaIcons
import com.sun.module_base.app.ResultState
import com.sun.module_base.ext.click
import com.sun.module_common.event.getEventViewModel
import com.sun.module_base.ext.showToast
import com.sun.module_base.widget.HorizontalDottedProgressBar
import com.sun.module_common.model.UserInfo
import com.sun.module_common.route.RouteName
import com.sun.module_common.route.RouteUtils
import com.sun.module_common.sp.SpUtils
import com.sun.module_common.widget.AnimationView
import com.sun.module_common.widget.AppBar
import com.sun.module_network.utils.logi

/**
 *@author:sunc
 *@time :2025/7/28 17:25
 *@desc: 描述
 */
@Preview(showBackground = true)
@Composable
fun LoginScreen(
    modifier: Modifier = Modifier,
    viewModel: LoginViewModel = hiltViewModel<LoginViewModel>(),
) {
    val passwordInteractionState = remember { MutableInteractionSource() }
    val userInteractionState = remember { MutableInteractionSource() }

    var hasError by remember { mutableStateOf(false) }
    var passwordVisualTransformation by remember {
        mutableStateOf<VisualTransformation>(PasswordVisualTransformation())
    }
    LaunchedEffect(key1 = Unit) {
        viewModel.loginFlow.collect {
            when (it) {
                is ResultState.Error -> {
                    "网络请求失败".logi()
                    viewModel.isLoading = false
                    hasError = true
                }

                is ResultState.Loading -> {
                    "加载中".logi()
                    hasError = false
//                    viewModel.isLoading = true
                }

                is ResultState.Success<UserInfo?> -> {
                    "网络请求成功:$it".logi()
                    hasError = false
                    viewModel.isLoading = false
                    SpUtils.userInfo = it.data
                    SpUtils.isLogin = true
                    getEventViewModel().userInfo.emit(it.data)
                    showToast("登录成功")
                    RouteUtils.back()
                }
            }
//            showToast("登录成功")
        }
    }


    Box(modifier.fillMaxSize()) {
        AppBar(
            title = "登录",
            modifier = Modifier.align(Alignment.TopCenter),
            onBack = {
                RouteUtils.back()
            })
        Column(
            modifier = Modifier
                .fillMaxWidth(0.9f)
                .align(Alignment.Center)
//                .background(color = MaterialTheme.colorScheme.onPrimaryContainer)
                .padding(vertical = 10.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {

            AnimationView(
                LottieCompositionSpec.Asset("working.json"),
                iterations = 1,
                modifier = Modifier.height(200.dp)
            )
            OutlinedTextField(
                modifier = Modifier.fillMaxWidth(),
                value = viewModel.userName,
                leadingIcon = {
                    FaIcon(
                        faIcon = FaIcons.Phone,
                        tint = LocalContentColor.current.copy(alpha = 0.8f)
                    )
                },
                maxLines = 1,
                isError = hasError,
                keyboardOptions = KeyboardOptions(
                    keyboardType = KeyboardType.Text,
                    imeAction = ImeAction.Next
                ),
                colors = OutlinedTextFieldDefaults.colors(),
                label = { Text(text = "用户名") },
                placeholder = { Text("请输入用户名！") },
                interactionSource = userInteractionState,
                onValueChange = {
                    viewModel.userName = it
                })
            Spacer(Modifier.height(10.dp))
            OutlinedTextField(
                modifier = Modifier.fillMaxWidth(),
                value = viewModel.passWord,
                placeholder = { Text("请输入密码！") },
                leadingIcon = {
                    FaIcon(
                        faIcon = FaIcons.Key,
                        tint = LocalContentColor.current.copy(alpha = 0.8f)
                    )
                },
                maxLines = 1,
                keyboardOptions = KeyboardOptions(
                    keyboardType = KeyboardType.Password,
                    imeAction = ImeAction.Done
                ),
                colors = OutlinedTextFieldDefaults.colors(),
                isError = hasError,
                label = { Text(text = "密码") },
                interactionSource = passwordInteractionState,
                visualTransformation = passwordVisualTransformation,
                trailingIcon = {
                    FaIcon(
                        faIcon = if (passwordVisualTransformation != VisualTransformation.None) FaIcons.EyeSlash else FaIcons.Eye,
                        tint = LocalContentColor.current.copy(0.6f),
                        modifier = Modifier.click {
                            passwordVisualTransformation =
                                if (passwordVisualTransformation != VisualTransformation.None) {
                                    VisualTransformation.None
                                } else PasswordVisualTransformation()
                        })
                },

                onValueChange = {
                    viewModel.passWord = it
                })
            Spacer(Modifier.height(10.dp))
            Button(
                modifier = Modifier.fillMaxWidth(),
                onClick = { viewModel.login() }
            ) {
                if (viewModel.isLoading) {
                    HorizontalDottedProgressBar(color = MaterialTheme.colorScheme.onSurface)
                } else {
                    Text("登录")
                }
            }
            Spacer(Modifier.height(10.dp))
            Box(modifier = Modifier.fillMaxWidth(0.9f), contentAlignment = Alignment.BottomEnd) {
                Text("注册", modifier = Modifier.click {
                    RouteUtils.navigateTo(RouteName.Register)
                })
            }
        }

    }

}